<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index1 == 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightId(scope.row, item1.id)" closable>{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeRightId(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      @close="removeRightId(scope.row, item3.id)"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightvisible"
      width="50%"
      @close="closeRightDialog"
    >
      <el-tree :data="rightList" :props="treeProps" ref="rightTree" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightvisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      setRightvisible : false,
      rightList:[],
      role_id:null,
    //   树形控件绑定
      treeProps:{
          label:'authName',
          children:'children'
      },
      defKeys:[]
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) return this.$message.error("获取角色失败");

      this.roleList = res.data;

      console.log(this.roleList);
    },
    async removeRightId(role, id) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(role, id);
      if (confirmRes !== "confirm") return this.$message.info("取消删除");

      const { data: res } = await this.$http.delete(
        `/roles/${role.id}/rights/${id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败");

      role.children = res.data;
    },
    // 获取权限列表对话框
    async showSetRightDialog(role) {
        this.role_id = role.id
        const {data:res} = await this.$http.get('rights/tree')
        
        if(res.meta.status !==200) return this.$message.error('获取权限列表失败')
        this.rightList = res.data
        await this.getLeafKeys(role,this.defKeys)
        this.setRightvisible = true
        // console.log(this.defKeys)
    },
    // 使用递归获取角色的三级权限节点
    getLeafKeys(node,arr){
        // 判断是否是三级节点
        if(!node.children){
           return arr.push(node.id)
        }
        node.children.forEach(item=>this.getLeafKeys(item,arr)
        )
    },
    closeRightDialog(){
      this.defKeys = []
    },
    async submitRights(){
      let submitArray = [
        ...this.$refs.rightTree.getCheckedKeys(),
        ...this.$refs.rightTree.getHalfCheckedKeys()
      ]
      // console.log(submitArray)
      let submitParams = submitArray.join(',')
      
      const {data:res} = await this.$http.post(`roles/${this.role_id}/rights`,{rids:submitParams})

      if(res.meta.status !==200)return this.$message.error('授权失败')
      
      this.$message.success('授权成功')
      this.setRightvisible = false
      this.getRolesList();
    }
  },
};
</script>

<style lang="scss">
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>